package com.ciwong.epaper.modules.epaper.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.TrafficStats;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.HideDownloadDialogBean;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.adapter.ContentListAdapter2;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.HomeWorkUtil;
import com.ciwong.epaper.modules.epaper.util.MultipleServicesDialog;
import com.ciwong.epaper.modules.me.bean.CheckValidBean;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.ServicePermissionJudgeUtil;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.util.download.ProgressCircle;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.ContainerType;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.DownloadProgressBar;
import com.ciwong.mobilelib.widget.TitleBar;
import com.liulishuo.filedownloader.FileDownloadServiceProxy;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/13.
 * <p>
 *  新版本阅读，打开后的详情页面
 */

public class NewReadContentActivity extends BaseActivity {


    private ListView list_view;
    private String mBookId;
    private String mCid;
    private int mServiceId;
    private LinearLayout list_nodata, mLlNoNet;
    private Button mBtnRetry;

    private EpaperInfo mEpaperInfo;
    private CatalogueInfo mCatalogueInfo;
    private Module mModule;

    private boolean isformNewDesk = false;

    private int fromResource;

    private static final String TAG = "NewReadContentActivity";

    /**
     * 扫一扫数据所属的服务列表
     */
    private List<EpaperInfo.Server> mEpaperServerList;

    private Map<Integer, Module> versionIdMapMo = new HashMap<Integer, Module>();

    private ArrayList<Module> mModuleList = new ArrayList<>();
    private ContentListAdapter2 mContentListAdapter;

    private List<DownLoadInfo> mDownLoadInfos = new ArrayList<>();

    //    private boolean isCallBack = true;


    private Map<DownLoadInfo, Hoder> downLoadInfoMap = new HashMap<DownLoadInfo, Hoder>();
    //    private Handler mHandler = new Handler() {
    //        @Override
    //        public void handleMessage(Message msg) {
    //            isCallBack = true;
    //
    //        }
    //    };

    //获取通过Mobile连接收到的字节总数
    private long total_data = TrafficStats.getTotalRxBytes();

    /**
     * 模块内容
     */
    private List<ModuleContent> mResourceList = new ArrayList<>();
    private String mTitleName;

    @Override
    protected void preCreate() {
        isformNewDesk = getIntent().getBooleanExtra(BaseIntentFlag.INTENT_FLAG_FORM, false);
//        fromResource = getIntent().getIntExtra(BaseIntentFlag.INTENT_FLAG_ACTION, IntentValue.JumpToBookCatalogType.NORMAL);
//        if (isformNewDesk) {
//            mBookId = getIntent().getStringExtra(BaseIntentFlag.INTENT_FLAG_BOOKID);
//            mCid = getIntent().getStringExtra(BaseIntentFlag.INTENT_FLAG_CID);
//            mTitleName = getIntent().getStringExtra(BaseIntentFlag.INTENT_FLAG_TITLE);
//        } else {
//            mEpaperInfo = (EpaperInfo) getIntent()
//                    .getSerializableExtra(BaseIntentFlag.INTENT_FLAG_OBJ);
//            mCatalogueInfo = (CatalogueInfo) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_CATALOGUE_INFO);
//
//
//            //        from = getIntent().getIntExtra(BaseIntentFlag.INTENT_FLAG_ACTION,
//            //                IntentValue.JumpToBookCatalogType.NORMAL);
//            //服务器没有数据所以先用死的
//            if (mEpaperInfo != null) {
//                mBookId = mEpaperInfo.getPackageId();
//            }
//
//            if (mCatalogueInfo != null) {
//                mCid = mCatalogueInfo.getId();
//            }
//
//            //        mEpaperInfo = (EpaperInfo) getIntent().getSerializableExtra(BaseIntentFlag.INTENT_FLAG_OBJ);
//            mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
//            mEpaperServerList = (List<EpaperInfo.Server>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);
//        }


    }

    @Override
    protected int setView() {
        return R.layout.activity_new_content;
    }


    @Override
    protected void findViews() {
        titleBar = (TitleBar) findViewById(R.id.activity_base_titlebar);
        list_view = (ListView) findViewById(R.id.list_view);
        list_nodata = findViewById(R.id.list_nodata);
        mBtnRetry = findViewById(R.id.btn_retry);
        mLlNoNet = findViewById(R.id.ll_no_net);
        list_view.setOnItemClickListener(onItemClickListener);
        mBtnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadNetData();
            }
        });
    }

    @Override
    protected void initEvent() {
        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                if (mCurrentDownloadInfo != null) {
                    int status = mCurrentDownloadInfo.getStatus();
                    if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                        DownLoad.getInstance().pauseTask(mCurrentDownloadInfo);
                    }
                }
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    protected void init() {
        Log.e(TAG, "init:  这里是展示数据的页面....");
        if (isformNewDesk) {
            titleBar.setTitle(mTitleName);
        } else {
            titleBar.setTitle(mCatalogueInfo.getName());
        }
        mContentListAdapter = new ContentListAdapter2(NewReadContentActivity.this, mResourceList, versionIdMapMo);
        list_view.setAdapter(mContentListAdapter);
    }

    @Override
    protected void loadData() {
        //        mBookId = "2760";
        //        mCid = "3192";
        getLocData();
    }

    @Override
    protected void onResume() {
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        DownLoadInfo info = item.getInfo();
        if (info != null) {
            Hoder hoder = findHoder(info);
            mCurrentDownloadInfo = info;
            dealCircleProgress(info, hoder);
        }

    }


    private Hoder findHoder(DownLoadInfo info) {
        for (DownLoadInfo key : downLoadInfoMap.keySet()) {
            if (key.getModuleId().equals(info.getModuleId()) && key.getVersionId().equals(info.getVersionId())) {
                //                debug("----------keykey-------------" + key.getChapterId() + "-----固定的info------" + info.getChapterId() + "---------name--" + key.getChapterName() + "----" + info.getChapterName());
                return downLoadInfoMap.get(key);
            }
        }
        return null;
    }

    /**
     * 获取本地数据
     */
    private void getLocData() {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_CHAPTER + mBookId + mCid, new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        loadNetData();
                    }

                    @Override
                    public void failed(Object data) {
                        loadNetData();
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            if (data != null) {
                                //获取本地DownLoadInfos
                                mModuleList = (ArrayList<Module>) data;
                                //获取缓存数据
                                if (mModuleList != null) {

                                    paraData();
                                    if (isformNewDesk) {//新的同步教材过来的时候 改变加入数据库的方式  在点击下载的时候判断有没有加入数据库

                                    } else {
                                        mDownLoadInfos = DownLoadDB.queryDownloadInfoByBookIdAndChapterId(mBookId, mCid, CatalogueInfo.PackageMode.PACKAGE_MODE_NEW);
                                        mDownLoadInfos = fillList(mResourceList);
                                    }

                                    updateUI();
                                }
                            }
                            loadNetData();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }


    private void loadNetData() {

        EpaperDao.getInstance().getCatalogueResourceList(mBookId, mCid, null, isformNewDesk, fromResource,

                new BaseExtCallBack(NewReadContentActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void success(final Object data) {
                        try {
                            //后台没数据临时用之前的接口
                            mModuleList = (ArrayList<Module>) data;
                            if (mModuleList == null || mModuleList.size() == 0) {
                                showContainerType(ContainerType.TYPE_NO_DATA);
                            } else {
                                showContainerType(ContainerType.TYPE_HAVE_DATA);
                                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_CHAPTER + mBookId + mCid, mModuleList);
                                paraData();


                                if (isformNewDesk) {

                                } else {
                                    mDownLoadInfos = DownLoadDB.queryDownloadInfoByBookIdAndChapterId(mBookId, mCid, CatalogueInfo.PackageMode.PACKAGE_MODE_NEW);

                                    mDownLoadInfos = fillList(mResourceList);
                                }

                                updateUI();
                            }


                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        //网络获取失败了再走本地获取流程
                        super.failed(errorCode, data);
                        if (mModuleList == null || mModuleList.size() == 0) {
                            if (!NetworkUtils.isOnline() || data instanceof TimeoutError) {
                                showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                            } else if (errorCode != 17 && errorCode != 27) {
                                ToastUtil.INSTANCE.toastCenterError(R.string.server_error);
                            }
                        }


                    }

                    @Override
                    public void failed(Object data) {
                        //                        getLocData();
                        super.failed(data);
                        if (mModuleList == null || mModuleList.size() == 0) {
                            if (!NetworkUtils.isOnline() || data instanceof TimeoutError) {
                                showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                            }
                        }

                    }
                });
    }

    private void showContainerType(ContainerType containerType) {
        if (containerType == ContainerType.TYPE_NO_NET_FAILED) {
            mLlNoNet.setVisibility(View.VISIBLE);
            list_view.setVisibility(View.GONE);
            list_nodata.setVisibility(View.GONE);
        } else if (containerType == ContainerType.TYPE_NO_DATA) {
            list_nodata.setVisibility(View.VISIBLE);
            mLlNoNet.setVisibility(View.GONE);
            list_view.setVisibility(View.GONE);
        } else {
            list_view.setVisibility(View.VISIBLE);
            mLlNoNet.setVisibility(View.GONE);
            list_nodata.setVisibility(View.GONE);
        }

    }

    private void paraData() {
        versionIdMapMo.clear();
        mResourceList.clear();
        for (Module module : mModuleList) {
            List<ModuleContent> moduleContentList = module.getResourceList();
            if (null != moduleContentList && moduleContentList.size() > 0) {
                for (int i = 0; i < moduleContentList.size(); i++) {
                    ModuleContent moduleContent = moduleContentList.get(i);
                    if (TextUtils.isEmpty(moduleContent.isDeleted) || !moduleContent.isDeleted.equals("1")) {//单元没有被删除
                        mResourceList.add(moduleContentList.get(i));
                        versionIdMapMo.put(mResourceList.size(), module);
                    }
                }
            }
        }


    }

    private void updateUI() {
        mContentListAdapter.updateData(mResourceList, versionIdMapMo, mDownLoadInfos);
    }


    /**
     * 解析从网络获取的章节信息并填充列表
     */
    private List<DownLoadInfo> fillList(List<ModuleContent> moduleContentList) {
        List<DownLoadInfo> downLoadInfos = new ArrayList<DownLoadInfo>();
        List<DownLoadInfo> tempList = new ArrayList<DownLoadInfo>();

        parseCatalogueList(downLoadInfos, moduleContentList);

        out:
        for (DownLoadInfo info : downLoadInfos) {
            if (info == null) {
                continue;
            }
            // 一本书有可能新包就包混合，必须每个章节判断是否是新资源
            for (DownLoadInfo downLoadInfo : mDownLoadInfos) {
                // 书的章节结构没有变化的, 需要记住下载状态,下载失败重下，预防资源变化，下载地址变化

                if (downLoadInfo != null && downLoadInfo.getModuleId().equals(info.getModuleId()) && downLoadInfo.getVersionId().equals(info.getVersionId()) && downLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {

                    downLoadInfo.setChapterName(info.getChapterName());
                    downLoadInfo.setUrl(info.getUrl());
                    downLoadInfo.setSavePath(info.getSavePath());
                    downLoadInfo.setSize(info.getSize());
                    downLoadInfo.setIsFree(mEpaperInfo.getIsFree());
                    downLoadInfo.setIsKaoShi(mEpaperInfo.getRequired());

                    tempList.add(downLoadInfo);
                    Log.d("DownLoadInfos", "#####for  insertDetail############");
                    if (downLoadInfo.getStatus() == DownloadStatus.STATUS_DOWNLOADING) {
                        downLoadInfo.setStatus(DownloadStatus.STATUS_PAUSE);
                    }

                    DownLoadDB.insertDetail(downLoadInfo);
                    continue out;
                }
            }

            if (info.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
                // 新增章节插入
                DownLoadInfo newDownLoadInfo = new DownLoadInfo();
                newDownLoadInfo.setBookId(mBookId);
                newDownLoadInfo.setChapterId(mCid);
                newDownLoadInfo.setBookName(mEpaperInfo.getProductName());
                newDownLoadInfo.setIconUrl(mEpaperInfo.getCover());
                newDownLoadInfo.setIsFree(mEpaperInfo.getIsFree());
                newDownLoadInfo.setIsKaoShi(mEpaperInfo.getRequired());

                newDownLoadInfo.setVersionId(info.getVersionId());
                //新旧包结构区分
                newDownLoadInfo.setType(CatalogueInfo.PackageMode.PACKAGE_MODE_NEW);
                newDownLoadInfo.setModuleId(info.getModuleId());
                newDownLoadInfo.setChapterName(info.getChapterName());
                newDownLoadInfo.setUrl(info.getUrl());
                newDownLoadInfo.setSavePath(info.getSavePath());
                newDownLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                newDownLoadInfo.setSize(info.getSize());
                newDownLoadInfo.setResourceName(info.getResourceName());
                newDownLoadInfo.setResourceType(info.getResourceType());


                tempList.add(newDownLoadInfo);
                DownLoadDB.insertDetail(newDownLoadInfo);
                Log.d("DownLoadInfos", "#####getType  insertDetail############");

            }

        }


        return tempList;
    }


    /**
     * 从网络下载的数据catalogueInfos，递归获取小题和子题，放至downLoadInfos中
     *
     * @param downLoadInfos
     */
    private void parseCatalogueList(List<DownLoadInfo> downLoadInfos,
                                    List<ModuleContent> moduleContentList) {

        DownLoadInfo downLoadInfo = null;
        //
        for (int i = 0; i < moduleContentList.size(); i++)
        //        for (ModuleContent moduleContent : moduleContentList)
        {
            ModuleContent moduleContent = moduleContentList.get(i);
            if (moduleContent != null) {

                Module module = versionIdMapMo.get(i + 1);

                String url = moduleContent.getResourceUrl();
                downLoadInfo = new DownLoadInfo();
                downLoadInfo.setUrl(url);
                downLoadInfo.setChapterId(mCatalogueInfo.getId());
                downLoadInfo.setChapterName(mCatalogueInfo.getName());
                downLoadInfo.setHash(mCatalogueInfo.getHash());
                downLoadInfo.setIsFree(mEpaperInfo.getIsFree());

                downLoadInfo.setSavePath(FileUtil.getSavePathByUrl(NewReadContentActivity.this, url));
                //新旧包结构区分
                downLoadInfo.setType(CatalogueInfo.PackageMode.PACKAGE_MODE_NEW);
                downLoadInfo.setResourceName(moduleContent.getResourceName());
                downLoadInfo.setResourceType(moduleContent.getResourceType());
                if (null != module) {
                    downLoadInfo.setModuleId(String.valueOf(module.getModuleInfo().getModuleId()));

                }
                downLoadInfo.setVersionId(moduleContent.getVersionId());
                String fileSize = moduleContent.getFileSize();
                if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                    downLoadInfo.setSize(fileSize.split(" ")[0]);
                }

                downLoadInfos.add(downLoadInfo);

                //                if (catalogueInfo.getChildren() != null && catalogueInfo.getChildren().size() != 0) {
                ////                    parseCatalogueList(downLoadInfos,
                ////                            catalogueInfo.getChildren());
                //                }
            }
        }
    }


    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {

            if (DoubleClickCheckUtils.vertifyDuration()) {
                ModuleContent moduleContent = mResourceList.get(position);
                mModule = versionIdMapMo.get(position + 1);
                //这里有2种查询下载状态数据库的方法  老的书桌过来时在查询列表里面去找
                //新的同步教材过来是在下载的过程中去查找然后下载  插入数据库
                DownLoadInfo downLoadInfo;
                if (isformNewDesk) {
                    downLoadInfo = getDownLoadInfoFormNewDesk(moduleContent, mModule);
                } else {
                    downLoadInfo = getDownLoadInfo(moduleContent, mModule);
                }

                mCurrentClickDownloadInfo = downLoadInfo;
                Hoder hoder = new Hoder();
                hoder.imageView_download = (ImageView) convertView.findViewById(R.id.item_iocn);
                doClickListener(moduleContent, downLoadInfo, hoder, position, true);
//                showGetPermissDialog(moduleContent, downLoadInfo, hoder, position, true);
            }


        }
    };
    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, final Hoder hoder, final int position, final boolean isHandClick) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss(moduleContent, downLoadInfo, hoder, position, true);
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss(moduleContent, downLoadInfo, hoder, position, true);
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, final Hoder hoder, final int position, final boolean isHandClick) {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                doClickListener(moduleContent, downLoadInfo, hoder, position, true);
                            }
                        }
                    });
        } else {
            doClickListener(moduleContent, downLoadInfo, hoder, position, true);
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_REQUEST_WRITESD_PERMISSION:
                    break;
            }
        }
    }

    /**
     * item监听事件
     *
     * @param downLoadInfo
     */
    public void doClickListener(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, Hoder hoder, int position, boolean isHandClick) {


        if (ModuleInfo.ModuleInfoId.MODULE_ID_ESSAY == Integer.valueOf(downLoadInfo.getModuleId())) {
            //新闻不用下载资源
            downloadComplete(moduleContent, downLoadInfo, position, isHandClick);
            return;
        }

        if (TextUtils.isEmpty(downLoadInfo.getUrl())) {
            showToastError(R.string.package_no_publish2);
            return;
        }


        downLoadInfoMap.put(downLoadInfo, hoder);
        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_NORMAL:
            case DownloadStatus.STATUS_FAILED:
            case DownloadStatus.STATUS_FAILED_SDISFULL:
            case DownloadStatus.STATUS_FAILED_UNZIP:
            case DownloadStatus.STATUS_UPZIPING:
                if (DialogUtil
                        .sdIsFullForDownload(NewReadContentActivity.this, downLoadInfo)) {
                    DialogUtil.showSdFullDialog(
                            NewReadContentActivity.this,
                            downLoadInfo.getSize());
                    return;
                }

                judgeDownloadMethod(moduleContent, downLoadInfo, hoder, position);
                break;
            case DownloadStatus.STATUS_LOADING:
                //                DownLoad.getInstance().pauseTask(downLoadInfo);
                DownLoad.getInstance().resumeTask(downLoadInfo);
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                DownLoad.getInstance().pauseTask(downLoadInfo);
                break;
            case DownloadStatus.STATUS_PAUSE:
                if (NetworkUtils.isOnline()) {
                    if (NetworkUtils.isWifiOnline()) {
                        showDownloadDialog(downLoadInfo, moduleContent, hoder, position);
                        DownLoad.getInstance().resumeTask(downLoadInfo);
                    } else {
//                        DialogUtil.showWIFIDialogOfNewContent(
//                                NewReadContentActivity.this,
//                                downLoadInfo, moduleContent, hoder, position);
                    }
                } else {
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                }
                break;
            //            case DownloadStatus.STATUS_UPZIPING:
            //                // DownLoad.getInstance().addTask(info);
            //                break;
            case DownloadStatus.STATUS_COMPLETED:
                //新包拆分逻辑增加 资源 versionId,
                //                        String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(downLoadInfo.getBookId(), downLoadInfo.getChapterId());
                String resourcePath = ESystem.getPackagesJsonPathNew(downLoadInfo.getBookId(), downLoadInfo.getChapterId(), downLoadInfo.getModuleId(), moduleContent.getVersionId());
                //服务权限判断，跳转资源详情页

                if (new File(resourcePath).exists()) {
                    downloadComplete(moduleContent, downLoadInfo, position, isHandClick);
                    //                            EpaperJumpManager.jumpToContent(R.string.go_back, NewContentActivity2.this, downLoadInfo, mServiceId, mEpaperInfo, mEpaperServerList);
                } else {
                    downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                    downLoadInfo.setProgress(0);
                    judgeDownloadMethod(moduleContent, downLoadInfo, hoder, position);
                }

                break;
        }
    }

    private void judgeDownloadMethod(ModuleContent moduleContent, DownLoadInfo downLoadInfo, Hoder hoder, int position) {
        if (NetworkUtils.isOnline()) {
            if (NetworkUtils.isWifiOnline()) {
                showDownloadDialog(downLoadInfo, moduleContent, hoder, position);
                DownLoad.getInstance()
                        .addTask(downLoadInfo);
            } else {
//                DialogUtil.showWIFIDialogOfNewContent(
//                        NewReadContentActivity.this,
//                        downLoadInfo, moduleContent, hoder, position);
            }
        } else {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }

    }

    private void downloadComplete(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, int modulePosition, boolean isHandClick) {


        //        final ModuleContent moduleContent = mResourceList.get(modulePosition);
        mModule = versionIdMapMo.get(modulePosition + 1);
        //要区分是从扫一扫进来还是书桌进来的
        //如果最后都未空说明没购买没试用
        //        mServiceDetail = null;

        int position = 0;
        List<ModuleContent> moduleContentList = mModule.getResourceList();
        for (int i = 0; i < moduleContentList.size(); i++) {
            //versionId parentVersionId resourceType 确定唯一性
            if (moduleContent.getVersionId().equals(moduleContentList.get(i).getVersionId()) && moduleContent.getParentVersionId().equals(moduleContentList.get(i).getParentVersionId())) {
                position = i;
                break;
            }
        }
        final int moduleId;
        if (downLoadInfo != null && downLoadInfo.getType() == 1) {
            moduleId = Integer.parseInt(downLoadInfo.getModuleId());
        } else {
            moduleId = mModule.getModuleInfo().getModuleId();
        }

        //
        //        if (!isCallBack) {
        //            return;
        //        }
        //
        //        if (moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW && moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
        //            isCallBack = false;
        //        }
        if (!isHandClick) {
            boolean downloadInfoTheSame = HomeWorkUtil.isDownloadInfoTheSameToClickDownLoadInfo(downLoadInfo, mCurrentClickDownloadInfo);

            //下载完成自动打开判断是否下载框还存在，如果不存在，不往下走
            if (!isDownloadProessBarShowing()) {
                return;
            }

            //解决打开两个不同类型作业问题
            if (!downloadInfoTheSame) {
                if (FileDownloadServiceProxy.getImpl().isIdle()) {
                    hideDownloadProgress();
                }
                return;
            }
        }


        //下载完成手动打开，加个下载加载框
        if (isHandClick) {
            showDownloadProgress();
            hideCancelButtonOfDownloadProgress();
        }


        //书桌进来
        //从首页同步教材进去   isFromDesk 不进行鉴权处理
        boolean isFromDesk = isformNewDesk;
        if (!isFromDesk) {
            if (fromResource == IntentValue.JumpToBookCatalogType.FROM_RESOURCE_CENTER_DICTATION) {
                isFromDesk = true;
            }
        }
        ServicePermissionJudgeUtil.servicePermissionFilter2(NewReadContentActivity.this, downLoadInfo, mModule, mEpaperInfo, moduleContent, mServiceId, mEpaperServerList, position, false, isFromDesk, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideDownloadProgress();
                //                mHandler.sendEmptyMessageDelayed(0, 2000);
            }

            @Override
            public void failed(Object data) {
                hideDownloadProgress();
                //                mHandler.sendEmptyMessageDelayed(0, 2000);
            }

            @Override
            public void success(Object data) {
                final CheckValidBean checkValidBean = (CheckValidBean) data;
                //                mHandler.sendEmptyMessageDelayed(0, 2000);
                //没有权限
                if (mServiceId == -1 && null != checkValidBean && checkValidBean.isValid == 0) {
                    //扫描特有 逻辑
                    MultipleServicesDialog.OnServicesItemClick onServicesItemClick = new MultipleServicesDialog.OnServicesItemClick() {
                        @Override
                        public void onServicesItemClick(int position) {
                            MeJumpManager.jumpBuyService(NewReadContentActivity.this, R.string.go_back, checkValidBean.services.get(position).id, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, checkValidBean.msg);
                        }
                    };


                    MultipleServicesDialog multipleServicesDialog = new MultipleServicesDialog(NewReadContentActivity.this, checkValidBean.services, onServicesItemClick);
                    try {//有可能已经退出扫码界面，才请求到权限。防止崩溃。

                        if (checkValidBean.services.size() == 1) {
                            MeJumpManager.jumpBuyService(NewReadContentActivity.this, R.string.go_back, checkValidBean.services.get(0).id, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, checkValidBean.msg);
                        } else {
                            multipleServicesDialog.show();
                            multipleServicesDialog.setTitle(checkValidBean.msg);
                        }

                    } catch (Exception e) {

                    } finally {


                    }

                }


            }
        });

    }

    private void dealCircleProgress(final DownLoadInfo downLoadInfo, Hoder hoder) {
        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_FILE_DOWNLOAD:
                hideDownloadHorizontalProgressBar();
                hideCancelButtonOfDownloadProgress();
                break;
            case DownloadStatus.STATUS_COMPLETED:
                String resourcePath = ESystem.getPackagesJsonPathNew(downLoadInfo);

                if (new File(resourcePath).exists()) {
                    if (mCurrentModuleContent != null && mCurrentHolder != null) {
                        //                        doClickListener(mCurrentModuleContent,mCurrentDownloadInfo,mCurrentHolder,mCurrentPostion,false);
                        downloadComplete(mCurrentModuleContent, downLoadInfo, mCurrentPostion, false);
                    } else {
                        hideDownloadProgress();
                    }
                } else {
                    //这个状态表示没有下载成功
                    downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                    downLoadInfo.setProgress(0);
                    ThreadTask.getInstance().executorDBThread(new Runnable() {
                        public void run() {
                            DownLoadDB.insertDetail(downLoadInfo);
                        }
                    }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
                    hideDownloadProgress();
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                }
                break;
            case DownloadStatus.STATUS_FAILED:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_SDISFULL:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_UNZIP:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                //                Log.e(TAG, "onEventMainThread STATUS_DOWNLOADING: "+downLoadInfo.getChapterName()+"  "+downLoadInfo.getResourceName()+"  progress"+downLoadInfo.getProgress() );
                if (HomeWorkUtil.isDownloadInfoTheSameToClickDownLoadInfo(downLoadInfo, mCurrentClickDownloadInfo)) {
                    updateDownloadProgress(downLoadInfo.getProgress());
                }
                break;
        }
    }

    /**
     * 获取时间
     *
     * @return
     */
    private String getMil(int mil) {
        int sco = mil / 60;
        int miao = mil % 60;
        String fenz;
        if (sco < 10) {
            fenz = "0" + sco;
        } else if (sco > 59) {
            return "59:59";
        } else {
            fenz = sco + "";
        }
        String miaoZ;
        if (miao < 10) {
            miaoZ = "0" + miao;
        } else {
            miaoZ = miao + "";
        }
        return fenz + ":" + miaoZ;
    }

    /**
     * 得到当前网速
     *
     * @return
     */
    private long getNetSpeed() {
        long traffic_data = TrafficStats.getTotalRxBytes() - total_data;
        total_data = TrafficStats.getTotalRxBytes();
        return traffic_data / 1024;
    }

    public static class Hoder {
        public ProgressCircle progressCircle;
        public ImageView imageView_download;
        public TextView speedText;
        public TextView sizeText;
    }


    private DownLoadInfo getDownLoadInfo(ModuleContent moduleContent, Module module) {
        DownLoadInfo downLoadInfo = null;
        if (mDownLoadInfos != null && mDownLoadInfos.size() > 0) {
            for (int i = 0; i < mDownLoadInfos.size(); i++) {
                //                Log.d("xixin", "--------getLastViewgetDownLoadInfo-----" + mDownLoadInfoList.get(i).getChapterId() + "-------" + curInfo.getId());
                if (mDownLoadInfos.get(i).getModuleId().equals(String.valueOf(module.getModuleInfo().getModuleId())) && mDownLoadInfos.get(i).getVersionId().equals(moduleContent.getVersionId())) {
                    downLoadInfo = mDownLoadInfos.get(i);
                    Log.d("xixin", "--------getLastViewgetDownLoadInfo-----" + downLoadInfo.getStatus());
                    break;
                }
            }
        }
        return downLoadInfo;
    }

    /**
     * 来自新的首页同步教材  查询数据库方法
     *
     * @param moduleContent
     * @param module
     * @return
     */
    private DownLoadInfo getDownLoadInfoFormNewDesk(ModuleContent moduleContent, Module module) {
        DownLoadInfo downLoadInfo = null;
        try {

            downLoadInfo = DownLoadDB.queryDownloadInfoByBookIdAndChapterIdAndMoudleidAndVerid(module.getModuleInfo().getPackageId(),
                    module.getModuleInfo().getcId(),
                    module.getModuleInfo().getModuleId() + "",
                    moduleContent.getVersionId());
        } catch (Exception e) {
            e.getStackTrace();
        }
        try {
            if (null == downLoadInfo) {
                downLoadInfo = new DownLoadInfo();
                downLoadInfo.setBookId(module.getModuleInfo().getPackageId());
                downLoadInfo.setChapterId(module.getModuleInfo().getcId());
                downLoadInfo.setModuleId(module.getModuleInfo().getModuleId() + "");
                downLoadInfo.setVersionId(moduleContent.getVersionId());
                downLoadInfo.setChapterName(mTitleName);
                downLoadInfo.setResourceName(moduleContent.getResourceName());
                downLoadInfo.setUrl(moduleContent.getResourceUrl());
                downLoadInfo.setSize(moduleContent.getFileSize());
                downLoadInfo.setResourceType(moduleContent.getResourceType());
                downLoadInfo.setModuleName(module.getModuleInfo().getModuleName());
                //只有新资源
                downLoadInfo.setType(1);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }


        return downLoadInfo;
    }


    private DownLoadInfo mCurrentClickDownloadInfo;
    private DownLoadInfo mCurrentDownloadInfo;
    private ModuleContent mCurrentModuleContent;
    private int mCurrentPostion;
    private Hoder mCurrentHolder;

    public void showDownloadDialog(DownLoadInfo downLoadInfo, ModuleContent moduleContent, Hoder hoder, int position) {
        mCurrentModuleContent = moduleContent;
        mCurrentPostion = position;
        mCurrentHolder = hoder;
        showDownloadProgress();
        showCancelButtonOfDownloadProgress();
    }

    //隐藏加载框
    public void onEventMainThread(HideDownloadDialogBean hideDownloadDialogBean) {
        hideDownloadProgress();
    }


}
